package com.qf.blogsystem.controller.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "EncordingFilter",urlPatterns = "/*",initParams = {
        @WebInitParam(name = "encording", value = "utf-8")
})
public class EncordingFilter implements Filter {
    //声明编码类型
    private String encording;

    public void init(FilterConfig config) throws ServletException {
        //初始化时获得编码类型
        encording = config.getInitParameter("encording");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //类型转换
//        HttpServletRequest request= (HttpServletRequest) req;
//        HttpServletResponse response= (HttpServletResponse) resp;
        //设置请求处理编码
        req.setCharacterEncoding(encording);
        //设置响应编码
//        resp.setContentType("text/html;charset=" + encording);
        resp.setCharacterEncoding(encording);
        //放行
        chain.doFilter(req, resp);
    }

    public void destroy() {
    }

}
